import _ from 'underscore';
import dispatcher from 'lib/dispatcher';
import { Scope } from 'lib/scopeFactory';
import ApiFactory from 'lib/ApiFactory';

export default class MainScope extends Scope {
  constructor(props, context) {
    super(props, context);
    this.$state = {
      loading: false,
      elements: []
    };

    this.api = ApiFactory({
      url: function () {
        return `${BlueWare.urlPrefix}/app/${BlueWare.appId}/keytransaction.json`;
      }
    });
  }

  fetch() {
    this.$state.loading = true;
    this.emit();

    this.api().fetch().then((response) => {
      if (_.isArray(response.data)) {
        this.$state.elements = response.data;
      }

      this.$state.loading = false;
      this.emit();
    });
  }

  $remove({id, callback}) {
    // Ajax request...
    let api = ApiFactory({
      url: function (params) {
        return `${BlueWare.urlPrefix}/app/${BlueWare.appId}/keytransaction/${id}.json`;
      },
      method: 'DELETE'
    });

    api().fetch().then((res) => {
      // 消息提示
      callback(res.status === 'SUCC');

      // 查找当前元素的位置
      let index = _.findIndex(this.$state.elements, (element) => {
        return element.id === id;
      });

      if (index !== -1) {
        let elements = [
          ...this.$state.elements.slice(0, index),
          ...this.$state.elements.slice(index + 1)
        ];

        this.$state.elements = elements;
        this.emit();
      }
    });
  }

  $load() {
    this.fetch();
  }
}
